package com.lsp.helper;

import com.lsp.annotation.RequestMapping;
import com.lsp.bean.Handler;
import com.lsp.bean.Request;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 请求的处理器映射器，类似于spring mvc 的HandelMapping()
 *
 * 通过ClassHelper工具类获取class对象，判断带RequestMapping注解的方法封装为处理器（将注解里的请求路径封装成对象，放入REQUEST_HANDLER_MAP中）
 */
public class ControllerHelper {

    private static final Map<Request, Handler> REQUEST_HANDLER_MAP = new HashMap<>();

    static {
        Set<Class<?>> controllerClassSet = ClassHelper.getControllerClassSet();
        if(CollectionUtils.isNotEmpty(controllerClassSet)){
         for (Class<?> controllerClass : controllerClassSet){
             Method[] methods = controllerClass.getDeclaredMethods();
             if(ArrayUtils.isNotEmpty(methods)){
                 for(Method method : methods){
                     if(method.isAnnotationPresent(RequestMapping.class)){
                         RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);

                         //请求路径
                         String requestPath = requestMapping.value();

                         //请求方法
                         String requestMethod = requestMapping.method().name();

                         // 封装请求和处理器
                         Request request = new Request(requestMethod, requestPath);
                         Handler handler = new Handler(controllerClass, method);
                         REQUEST_HANDLER_MAP.put(request,handler);

                     }
                 }
             }
         }
        }
    }


    /**
     * 获取handler
     * @param requestMethod
     * @param requestPath
     * @return
     */
    public static Handler getHandler(String requestMethod, String requestPath){
        Request request = new Request(requestMethod, requestPath);
        return REQUEST_HANDLER_MAP.get(request);
    }
}
